<template>
  <!-- 围栏选项 -->
  <el-dialog class="my-dialog" title="选择坐标（在地图上点出坐标，双击结束，可编辑拉动坐标点，双击坐标点为删除坐标点）" :visible.sync="visible"
             width="90%" append-to-body @close="cancel">
    <div>
      <div id="container" class="mapPoint"></div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button type="danger" @click="clearFn" size="small" plain>清空区域</el-button>
      <el-button type="primary" @click="confirmAndClose" size="small" plain>确定并退出</el-button>
      <el-button @click="cancel" size="small">取 消</el-button>
    </div>
  </el-dialog>
</template>
<script>
export default {
  name: "mapPoint",
  props: ['visible', 'form'],
  data() {
    return {
      mapPosition: [],
      editorTool: null,
      polygon: null,
      overlays: null,
      map: null
    }
  },
  watch: {
    visible() {
      if (this.visible) {
        this.initMap()
      } else {
        this.clearFn()
      }
    }
  },
  created() {
  },
  methods: {
    // 在地图上绘画区域结束后
    drawPolygon() {
      let that = this
      that.map.setDefaultCursor("crosshair");
      this.map.plugin(["AMap.MouseTool", "AMap.PolyEditor"], function () {
        let mousetool = new AMap.MouseTool(that.map);
        mousetool.polygon();
        mousetool.on('draw', function (target) {
          // that.map.plugin(["AMap.PolyEditor"], function () {
          //   let polylineEditor = new AMap.PolyEditor(that.map, target.obj);
          //   polylineEditor.open();
          //   target.obj.editor = polylineEditor;
          // });
          //创建好图形 的时候打开新增窗口
          that.overlays = target.obj;//获取当前覆盖物对象
          that.setEvent(target.obj);//设置右键点击效果事件
        })
      })
    },
    // 结束多边形编辑
    setEvent(overlay) {
      //参数就是覆盖物
      //这个赋给全局变量一定要
      let that = this
      // that.getOverlayPathDataInfo();
      // 右键
      overlay.on("rightclick", function () {
        // that.overlays = overlay;
        // openEditWindow(overlay.fenceId,shape); //
        console.log('打开编辑框')
      });
      overlay.on("dblclick", function () {// 双击结束编辑
        if (overlay.editor != null) {
          overlay.editor.close();
          let option = that.overlays.getOptions();
          option.strokeColor = "#555";
          option.strokeWeight = "1";
          option.strokeOpacity = "0.5";
          that.overlays.setOptions(option);
          //向后台更新数据库信息
          that.getOverlayPathDataInfo();
        }
      });
    },
    clearFn() {
      console.log('this.overlays:', this.overlays)
      if (this.overlays) {
        this.overlays = [];
        this.map.clearMap(); // 清除地图上的所有覆盖物
        // this.overlays.setPath({path: []});
        // this.overlays.setPath(null);
        // this.map.remove(this.overlays);
        // this.map.removeLayer()
        // this.overlays = []
        // this.map.remove(this.overlays)
        // // this.map.removeOverlay();
        // this.map.clearMap();
        // // this.map.remove(this.overlays);
        // this.overlays = null
        // this.map.removeOverlay()
      }
    },
    //获取多边形或者圆形的组成信息
    getOverlayPathDataInfo() {
      if (this.overlays) {
        let pointsCount = this.overlays.getPath().length;
        let polygonArr = new Array(); //构建多边形经纬度坐标数组
        let munityAreaList = []
        console.log('pointsCount', pointsCount)
        for (let i = 0; i < pointsCount; i++) {
          polygonArr.push(new AMap.LngLat(this.overlays.getPath()[i].lng, this.overlays.getPath()[i].lat));
          let pointObj = new Object();
          pointObj.lat = this.overlays.getPath()[i].lat;
          pointObj.lng = this.overlays.getPath()[i].lng;
          munityAreaList[i] = pointObj;
        }
        return munityAreaList
      } else {
        return false
      }
    },
    //确定并退出
    confirmAndClose() {
      if (!this.getOverlayPathDataInfo()) {
        this.$message.error('请点出区域坐标内容')
      } else {
        this.$emit('getPoint', JSON.stringify(this.getOverlayPathDataInfo()))
        this.cancel()
      }
    },
    initMap() {
      let that = this
      this.$nextTick(() => {
        let center = that.$MapCenter
        let MapZoom = that.$MapZoom
        if(this.form.lon && this.form.lat){
          center = [this.form.lon, this.form.lat]
          MapZoom = 17
        }
        that.map = new AMap.Map('container', {
          mapStyle: "amap://styles/whitesmoke", //设置地图的显示样式
          resizeEnable: true,
          center: center,
          zoom: MapZoom
        })
        // let mapType = new AMap.MapType({defaultType: 1});
        // that.map.addControl(mapType);
        that.drawPolygon()
        // 是否有默认的坐标
        if (that.form.rangePoints) {
          that.initAreaFn()
        }
      })
    },
    cancel() {
      this.$emit('update:visible', false)
    },
    // 展示已有数据
    initAreaFn() {
      let that = this
      let polygonArray = JSON.parse(this.form.rangePoints); //构建多边形经纬度坐标数组
      let arr = [];
      for (let point of polygonArray) {
        arr.push(new AMap.LngLat(point.lng, point.lat));
      }
      let poly = new AMap.Polygon({
        map: that.map,
        path: arr,
        strokeColor: "#555",
        strokeOpacity: 0.5,
        strokeWeight: 1.5,
        fillColor: "#d67ea7",
        fillOpacity: 0.35
      });
      poly.setMap(that.map);
      // this.map.add(poly)
      // this.setEvent(poly);
      // this.polyAndCircle.push(poly);//保存界面上的图形
      this.overlays = poly;
      // this.map.plugin(["AMap.PolyEditor"], function () {
      //   var polylineEditor = new AMap.PolyEditor(that.map, that.overlays);
      //   that.overlays.editor = polylineEditor;
      // });
      // this.overlays.editor.open();
      let option = this.overlays.getOptions();
      option.strokeColor = "#ff0000";
      option.strokeWeight = "3";
      option.strokeOpacity = "0.5";
      this.overlays.setOptions(option);
    }
  }
}
</script>

<style scoped>
.mapPoint {
  width: 100%;
  height: 500px;
}

</style>
